//
//  AppDelegate.swift
//  JKTools
//
//  Created by 姜奎 on 2021/4/1.
//
import Foundation
import Cocoa
import ServiceManagement
@main
class AppDelegate: NSObject, NSApplicationDelegate {
    var download = false
    
    @IBOutlet weak var menus: NSMenu!
    
    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {

        self.statusItem.menu = self.menus
        self.statusItem.isVisible = true
        loadStatusItem(download: false)
        let isFirstStartApp = UserDefaults.checkAndRegisterFirstStartApp()

        if isFirstStartApp {
            AppleScriptCommand.installJKToolAppleScript { _ in
                
            }

            resetJKTool()
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        NSStatusBar.system.removeStatusItem(statusItem)
    }
    
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        if !flag {
            sender.activate(ignoringOtherApps: true)
            let window = sender.windows.first
            window?.makeKeyAndOrderFront(self)
            return true
        }
        return false
    }

    @IBAction func installAppleScript(_ sender: NSMenuItem) {
        AppleScriptCommand.installJKToolAppleScript { _ in

        }
    }
    @IBAction func clean(_ sender: NSMenuItem?) {
        UserDefaults.cleanBookmarkDatas()
    }

    @IBAction func resetJKToolScript(_ sender: NSMenuItem?) {
        resetJKTool()
    }

    @IBAction func uploadJKTool(_ sender: NSMenuItem) {
        uploadJKTool()
    }

    @IBAction func exit(_ sender: Any) {
        NSApplication.shared.terminate(self)
    }
    
    func resetJKTool() {
        NSOpenPanel.open(directoryURL: URL(fileURLWithPath: FileManager.userDirectory())) { _ in
            let shell = ShellOutCommand.resetJKTool()
            do {
                try shellOut(to: shell)
                Alert.alert(message: "更新完成")
            } catch {
                let error = error as! ShellOutError
                Alert.alert(message: "更新失败：\(error.message)")
            }
        }
    }
}

extension AppDelegate {
    
    func loadStatusItem(download: Bool) {
        
        guard let button = statusItem.button else {
            return
        }
        DispatchQueue.main.async{
            if !download {
                let icon = NSImage(named: "Image")
                button.image = icon
            } else{//square.and.arrow.down
                let icon = NSImage(systemSymbolName: "square.and.arrow.down.on.square", accessibilityDescription: nil)
                button.image = icon
            }
        }
    }
}

extension AppDelegate {
    
    func uploadJKTool() {

        if self.download {
            return
        }
        self.download = true
        loadStatusItem(download: true)

        NSOpenPanel.open(directoryURL: URL(fileURLWithPath: FileManager.userDirectory())) { _ in
            let shell = ShellOutCommand.updateJKTool()
            do {
                try shellOut(to: shell)
                Alert.alert(message: "更新完成")
            } catch {
                let error = error as! ShellOutError
                Alert.alert(message: "更新失败：\(error.message)")
            }
            self.loadStatusItem(download: false)
            self.download = false
        }
    }
}

extension AppDelegate: NSMenuDelegate {
    func menuDidClose(_ menu: NSMenu) {
        NSApplication.shared.activate(ignoringOtherApps: true)
    }
}


